package com.usermanage.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;


import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

/**
 * Created by  on 2018/9/5
 */
@Slf4j
public class HttpUtil {

    /**
     * 接口调用 GET
     */
    public static String httpURLConectionGET(String GET_URL) {
        try {
            URL url = new URL(GET_URL);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接

            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("contentType", "application/json");
            connection.setRequestProperty("contentType", "UTF-8");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                log.info("￥￥￥￥￥￥2222222get返回数据******" + line);
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
            return null;
        }
    }

    /**
     * 接口调用  POST
     */
    public static String httpURLConnectionPOST(String POST_URL, String parm) {
        try {
            URL url = new URL(POST_URL);

            // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中

            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);

            // 设置连接输入流为true
            connection.setDoInput(true);

            // 设置请求方式为post
            connection.setRequestMethod("POST");

            connection.setRequestProperty("contentType", "application/json");
            // post请求缓存设为false
            connection.setUseCaches(false);

            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);

            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
            // application/x-javascript text/xml->xml数据
            //application/x-javascript->json对象
            //application/x-www-form-urlencoded->表单数据
            //这是重点^_^
//            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //设置超时时间
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();

            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());

            String parms = URLEncoder.encode(parm, "utf-8"); //URLEncoder.encode()方法  为字符串进行编码

            // 将参数输出到连接
            dataout.writeBytes(parms);

            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)

            System.out.println(connection.getResponseCode());

            // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                sb.append(bf.readLine());
            }
            bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接
            System.out.println(sb.toString());
            return sb.toString();


        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 接口调用发送post请求
     *
     * @param url
     * @param jsonData
     * @return
     */
    public static String post(String url, String jsonData) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000).setConnectionRequestTimeout(30000)
                    .setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("contentType", "application/json");
            List<NameValuePair> nameValuePairs = new ArrayList<>();
            nameValuePairs.add(new BasicNameValuePair("obj", jsonData));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity());
            log.error("**********" + result);
            return result;
        } catch (Exception e) {
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static String getDemo(String url) throws IOException {
        //实例化httpclient，（4.5新版本和以前不同），实例化方式有两种
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(30000).setConnectionRequestTimeout(30000)
                .setSocketTimeout(100000).build();
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:60.0) Gecko/20100101 Firefox/60.0");
        CloseableHttpResponse response = null;
        String result = null;
        try {
            /**
             * 底层http链接仍由响应对象保存
             * 允许直接从网络套接字流式传输响应内容
             * 为了确保正确释放系统资源
             * 用户必须从finally子句中调用CloseableHttpResponse #close()
             */
            response = httpClient.execute(httpGet);
            System.out.println(response.getStatusLine());
            HttpEntity entity = response.getEntity();
            //对响应主体做一些有用的事情
            //并确保他完全被消耗掉
            result = EntityUtils.toString(entity, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            response.close();
        }
        return result;
    }

    public static String httpPost(String url, Map<String, String> data) {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(100000).setConnectionRequestTimeout(100000)
                .setSocketTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

        try {
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            for (String key : data.keySet()) {
                list.add(new BasicNameValuePair(key, data.get(key)));
            }
            UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(entityParam);
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                return resultStr;
            }
        } catch (IOException e) {
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static String sendPost(String url, String data) {
        String response = null;
            try {
                    CloseableHttpClient httpclient = null;
                    CloseableHttpResponse httpresponse = null;
                    try {
                            httpclient = HttpClients.createDefault();
                            HttpPost httppost = new HttpPost(url);
                            StringEntity stringentity = new StringEntity(data,"UTF-8");
                            stringentity.setContentType("application/json");
                            httppost.setEntity(stringentity);
                            httpresponse = httpclient.execute(httppost);
                            response = EntityUtils
                                    .toString(httpresponse.getEntity());
                            log.info("response: " + response);
                        } finally {
                            if (httpclient != null) {
                                    httpclient.close();
                                }
                            if (httpresponse != null) {
                                   httpresponse.close();
                                }
                        }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            return response;
    }
//    public static String sendPost1(String url, String data) {
//        URL url = new URL(strURL);// 创建连接
//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//        connection.setDoOutput(true);
//        connection.setDoInput(true);
//        connection.setUseCaches(false);
//        connection.setInstanceFollowRedirects(true);
//        connection.setRequestMethod("POST");// 设置请求方式
//        connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
//        connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
//        connection.connect();
//        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
//        out.append(JSONUtil.object2JsonString(params));
//        out.flush();
//        out.close();
//
//
//    }

}
